import 'package:shared_preferences/shared_preferences.dart';

/**
 * 本地存储工具
 */
class SpUtils {
  SharedPreferences? prefs;

  //构造方法
  SpUtils._() {
    init();
  }

  static SpUtils? _instance;

/*   static preInit() {
    _instance ??= SpUtils._();
  } */

  SpUtils._pre(SharedPreferences prefs) {
    this.prefs = prefs;
  }

  ///预初始化，防止在使用get时，prefs还未完成初始化
  static Future<SpUtils?> preInit() async {
    if (_instance == null) {
      var prefs = await SharedPreferences.getInstance();
      _instance = SpUtils._pre(prefs);
    }
    return _instance;
  }

  static SpUtils? getInstance() {
    if (_instance == null) {
      _instance = SpUtils._();
    }
    return _instance;
  }

  void init() async {
    if (prefs == null) {
      prefs = await SharedPreferences.getInstance();
    }
  }

  setString(String key, String value) {
    prefs?.setString(key, value);
  }

  setDouble(String key, double value) {
    prefs?.setDouble(key, value);
  }

  setInt(String key, int value) {
    prefs?.setInt(key, value);
  }

  setBool(String key, bool value) {
    prefs?.setBool(key, value);
  }

  clear(String key) {
    prefs?.remove(key);
  }

  clearAll() {
    prefs?.clear();
  }

  bool? getBool(String key) {
    return prefs?.getBool(key) ?? false;
  }

  bool? getBool2(String key) {
    return prefs?.getBool(key) ?? true;
  }

  String? getString(String key) {
    return prefs?.getString(key);
  }

  int? getInt(String key) {
    return prefs?.getInt(key)?? 0;
  }

  int? getInt2(String key) {
    return prefs?.getInt(key) ?? 1;
  }

  
}
